﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iSun.Model;
using iSun.Entity;
using iSun.BLL.Base;
namespace iSun.Web.UI.Controls
{
    public class YuiTreeListPage : BasePage
    {

        /// <summary>
        /// 获取数据数据条件
        /// </summary>
        public string Condition
        {
            get
            {
                return GetStringFromQueryString("condition", "");
            }
        }



        /// <summary>
        /// 定义实体ID
        /// </summary>
        public override string EntityId
        {
            get
            {
                BaseEntity instance = iSun.Common.Reflection.CreateEntitysInstance(this.EntityName) as BaseEntity;
                if (instance != null)
                {
                    return instance.GetTableId();
                }
                return "ListId";
            }
        }

        public string Order
        {
            get
            {
                return GetStringFromQueryString("order", "");
            }
        }

        /// <summary>
        /// LIST to LIST UIList主实体
        /// </summary>
        public string MasterEntityName
        {
            get
            {
                return GetStringFromQueryString("masterentity", "DatDepartment");
            }
        }

        /// <summary>
        /// Querystring formatter:?masterPara=SysFunction(tablename)|Name(Caption)|FunctionID(key)|ParentID(ParentKey)|FunctionPath
        /// 主信息参数
        /// </summary>
        public string MasterPara
        {
            get
            {
                return GetStringFromQueryString("masterPara", "");
            }
        }

        /// <summary>
        /// 明细实体名
        /// </summary>
        public string DetailEntityName
        {
            get;
            set;
        }

        //关联字段
        private string _foreignKey = "";
        public string ForeignKey
        {
            get
            {
                return _foreignKey;
            }
            set
            {
                _foreignKey = value;
            }

        }



        /// <summary>
        /// 定义数据字段
        /// </summary>
        public string DataFields
        {
            get
            {
                return GetDataFields();
            }
        }

        /// <summary>
        /// 定义数据列
        /// </summary>
        public string DataColums
        {
            get
            {
                return GetColums();
            }
        }
              /// <summary>
        /// 按钮组
        /// </summary>
        public string BtnItems
        {
            get;
            set;
        }

        /// <summary>
        /// 按钮事件
        /// </summary>
        public string BtnEvents
        {
            get;
            set;
        }
        /// <summary>
        /// 初始化按钮事件
        /// </summary>
        public string InitBtnEvents
        {
            get;
            set;
        }
        /// <summary>
        /// 页面标题
        /// </summary>
        public string PageTitle
        {
            get
            {
                SysFunction entity = (new BaseBussnies(new SysFunction())).GetEntityByCondition<SysFunction>("functionid = '" + this.FunctionID + "'");
                if (entity == null)
                {
                    return "";
                }
                this.Page.Title = entity.Name;
                return entity.Name;
            }
        }

        public string StopAction
        {
            get
            {
                return "<script>if(window.frameElement)\n{alert(\"\");}\n</script>";
            }
        }
        private void SetTreeControl(System.Web.UI.Control ctrl)
        {
            foreach (System.Web.UI.Control c in ctrl.Controls)
            {
                if (c is TreeView)
                {
                    var tv1 = c as TreeView;
                    if (!string.IsNullOrEmpty(MasterPara))
                    {


                        string[] paras = MasterPara.Split('|');
                        if (paras.Length > 4)
                        {
                            tv1.TableName = paras[0];
                            tv1.Caption = paras[1];
                            tv1.Key = paras[2];
                            tv1.ParentKey = paras[3];
                            tv1.path = paras[4];
                            tv1.Condition = getRoleCondition();
                            if (Request.QueryString["ForeignKey"] != null)
                                ForeignKey = Request.QueryString["ForeignKey"].ToString();
                        }

                        if (paras.Length > 5 && tv1 != null)
                        {
                            tv1.AllowCheck = bool.Parse(paras[5].Trim());
                        }



                    }
                     
                    if (GetStringFromQueryString("DeptType", "") != "")
                    {
                        tv1.IsOutDepartment = GetStringFromQueryString("DeptType", "") == "0" ? 0 : 1;
                    }
                    else
                    {
                        if (Session["IsOutSite"] != null)
                        {
                            tv1.IsOutDepartment = (bool)Session["IsOutSite"] == true ? 1 : 0;
                        }
                    }
                    tv1.userID = User.EmpID;
                }
                else
                {
                    if (Request.QueryString["ForeignKey"] != null)
                        ForeignKey = Request.QueryString["ForeignKey"].ToString();
                    SetTreeControl(c);
                }
            }
        }
        protected override void OnLoad(System.EventArgs e)
        {

            // 权限 
            //if (this.UserId == null)
            //{
            //    Response.Redirect("/Error.aspx?message=1&functionId=" + FunctionID);
            //}
            //if (!CheckFunctionRight())
            //{
            //    Response.Redirect("/Error.aspx?message=2&functionId=" + FunctionID);
            //}

            iSun.BLL.Base.BaseBussnies bll = new BLL.Base.BaseBussnies();
            var list = bll.GetEntitysByCondition<iSun.Model.Entity>("EntityName='" + this.EntityName + "'");
            iSun.Model.Entity entity = list != null ? list.FirstOrDefault() : null;
            if (entity != null)
            {
                _width = entity.EditPageWidth;
                _height = entity.EditPageHeight;
            }
            // bll.GetEntitys
            SetButtons();
            SetTreeControl(this.Page);
            base.OnLoad(e);
        }
        public bool CheckFunctionRight()
        {
            iSun.BLL.BUser buser = new BLL.BUser();
            return buser.ExistFunction((System.Guid)this.UserId, (System.Guid)this.FunctionID);
        }
        public int _width;
        /// <summary>
        ///编辑页面宽
        /// </summary>
        public int EditWindowWidth
        {
            get
            {
                if (_width < 450)
                {
                    return 450;
                }
                return _width;
            }
            set
            {
                if (_width != value && value > 450)
                {
                    _width = value;
                }
            }
        }

        public int _height;
        /// <summary>
        ///编辑页面高
        /// </summary>
        public int EditWindowHeight
        {
            get
            {
                if (_height < 350)
                {
                    return 350;
                }
                return _height;
            }
            set
            {
                if (_height != value && value > 350)
                {
                    _height = value;
                }
            }
        }


        /// <summary>
        /// 定义样式
        /// </summary>
        public string DataTableCss
        {
            get
            {
                return GetColumsCss();
            }
        }


        /// <summary>
        /// 设置按钮操作权限
        /// </summary>
        public void SetButtons()
        {
            string functionid = GetStringFromQueryString("functionid", "");
            V_FunctionRight function = (new BaseBussnies(new V_FunctionRight())).GetEntityByCondition("FunctionID='" + functionid + "'") as V_FunctionRight;
            string userID = this.UserId.ToString();
            if (function == null)
            {
                BtnItems = "";
                BtnEvents = "";
                InitBtnEvents = "";
            }
            else
            {
                string[] btns = function.Opration.Split(',');
                string[] btnTexts = function.BarItems.Split(',');
                string[] fns = function.FnItems.Split(',');
                string[] barItems = (new BLL.BUser()).GetMenuOperation(userID, functionid)[0].Split(',').Distinct().ToArray();
                if (barItems == null)
                {
                    BtnItems = "";
                    BtnEvents = "";
                    InitBtnEvents = "";
                    return;
                }
                if (barItems.Count() == 0)
                {
                    BtnItems = "";
                    BtnEvents = "";
                    InitBtnEvents = "";
                    return;
                }
                //生成按钮
                StringBuilder strHTML = new StringBuilder("");
                StringBuilder strHTML2 = new StringBuilder("");
                StringBuilder strHTML3 = new StringBuilder("");

                for (int i = 0; i < btns.Length; i++)
                {
                    if (barItems.Contains(btns[i]))
                    {
                        string strFormater = "<button type=\"button\" id=\"{0}\" name=\"{0}\">{1}</button>\n";
                        strHTML.Append(string.Format(strFormater, btns[i], btnTexts[i]));

                        string strFormater2 = "  var {0} = new YAHOO.widget.Button(\"{0}\");\n {0}.on(\"click\", onButtonClick);\n";
                        strHTML2.Append(string.Format(strFormater2, btns[i]));

                        string strFormater3 = "                                      case \"{0}\":\n                                      {1}();\n                                       break;\n";
                        strHTML3.Append(string.Format(strFormater3, btns[i], fns[i]));
                    }
                }
                BtnItems = strHTML.ToString();
                BtnEvents = strHTML2.ToString();
                InitBtnEvents = strHTML3.ToString();
            }
        }


        /// <summary>
        /// 设置默认查询
        /// </summary>
        public string DefineCondition
        {
            get
            {
                iSun.BLL.Base.BaseBussnies bll = new BLL.Base.BaseBussnies();
                IList<QuerySolution> list = bll.GetEntitysByCondition<QuerySolution>("AddUser='" + this.UserId + "' and FunctionID='" + this.FunctionID + "' and IsDefault='Y'");
                if (list != null)
                {
                    QuerySolution entity = list.FirstOrDefault();
                    return entity == null ? "" : entity.Condition;
                }
                return "";
            }
        }
    
        /// <summary>
        /// 获取角色数据权限信息
        /// </summary>
        /// <returns></returns>
        public string getRoleCondition()
        {
            IList<Entity.SysRoleFunction> list = (new iSun.BLL.BUser()).GetRoleFunction(this.UserId, this.FunctionID);
            StringBuilder strCondition = new StringBuilder("");

            if (list == null)
            {
                return "";
            }
            foreach (var entity in list)
            {
                switch (entity.OperateRangeType.Trim())
                {
                    ///只能查看本人数据
                    case "0":
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        strCondition.Append(string.Format(" AddUser='{0}'", this.UserId));
                        break;
                    ///可以看本部门的
                    case "1":
                        if (this.EntityName == "V_CrmCustomer")
                        {
                            strCondition.Append(string.Format(" AreaId in  (select  VALUE  from  fn_Split((select DEPTIDS  from dbo.V_UserEmp  where userid='{0}'),',')) and IsPrevate='0'", this.UserId));
                        }
                        else
                        {
                            if (strCondition.ToString() != "")
                            {
                                strCondition.Append(" OR ");
                            }
                            strCondition.Append(string.Format(" AddUser in (select * from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        break;
                    // 全部数据
                    case "2":
                        break;
                    // 自定义条件数据
                    case "3":
                        //strCondition.Append(string.Format(" AddUser in (select * from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        break;
                    case "4":
                        break;
                    default:
                        break;
                }
            }

            //只用客户用户时使用
            if (this.User.IsOutsite == true)
            {
                if (this.EntityName == "TrActivity")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }

                    strCondition.Append(string.Format("(TrCustomerID='{0}')", User.CustomerID));

                }
                if (this.EntityName == "V_TrActivityCourse")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }

                    strCondition.Append(string.Format("(TrCustomerID = '{0}')", User.CustomerID));
                }


            }
            //if (this.EntityName == "V_TrStudyGain")
            //{
            //    if (strCondition.ToString() != "")
            //    {
            //        strCondition.Append(" OR ");
            //    }

            //    strCondition.Append(string.Format("(PrincipalHrmanno = '{0}')", this.UserId));
            //}

            return string.IsNullOrEmpty(strCondition.ToString()) ? "" : "(" + strCondition.ToString() + ")";
            //this.UserId
        }

        IList<DataListTemplate> list;
        /// <summary>
        /// 获取字段列
        /// </summary>
        /// <returns></returns>
        private string GetDataFields()
        {
            if (list == null)
            {
                DataListTemplate template = DataListTemplate.CreateInstance();
                BaseBussnies<DataListTemplate> bll = new BaseBussnies<DataListTemplate>(template);
                list = bll.GetEntityListByCondition<DataListTemplate>(" EntityName='" + EntityName + "'");
            }
            string _strHtml = "key:'{0}',label:'{1}',width:{2},{3}";
            if (list == null)
            {
                return ("{" + string.Format(_strHtml, "Not Data", "Not Data", 400) + "},");
            }
            StringBuilder _sbHtml = new StringBuilder("");
            var _list = list.Where(p => p.IsVisiable == "Y").OrderBy(p => p.iOrder).ToList();
            int i = 0;
            foreach (DataListTemplate _template in _list)
            {
                i = i + 1;
                //if (i == _list.Count())
                //{
                //    _sbHtml.Append("{" + string.Format(_strHtml, _template.Field, _template.THCaption,
                //        "100%"
                //        , string.IsNullOrEmpty(_template.DataFormatter) ? "sortable:true" : (_template.DataFormatter + ",sortable:true")) + "},");
                //}
                //else
                {
                    _sbHtml.Append("{" + string.Format(_strHtml, _template.Field, _template.THCaption,
                     (_template.Width > 0 ? _template.Width : 200)
                     , string.IsNullOrEmpty(_template.DataFormatter) ? "sortable:true,resizeable:true" : "formatter:" + (_template.DataFormatter + ",sortable:true,resizeable:true")) + "},");
                }
                if (i == 1)
                {
                    _sbHtml.Append("{" + string.Format(_strHtml, "iSun_Selected", "", 10, "formatter:\"checkbox\"") + "},");
                }


            }
            _sbHtml.Remove(_sbHtml.Length - 1, 1);
            return (_sbHtml.ToString());
        }



        private string GetDetailDataFields()
        {
            if (list == null)
            {
                DataListTemplate template = DataListTemplate.CreateInstance();
                BaseBussnies<DataListTemplate> bll = new BaseBussnies<DataListTemplate>(template);
                list = bll.GetEntityListByCondition<DataListTemplate>(" EntityName='" + EntityName + "'");
            }
            string _strHtml = "key:'{0}',label:'{1}',width:{2},{3}";
            if (list == null)
            {
                return ("{" + string.Format(_strHtml, "Not Data", "Not Data", 400) + "},");
            }
            StringBuilder _sbHtml = new StringBuilder("");
            var _list = list.Where(p => p.IsVisiable == "Y").OrderBy(p => p.iOrder).ToList();
            int i = 0;
            foreach (DataListTemplate _template in _list)
            {
                i = i + 1;
                //if (i == _list.Count())
                //{
                //    _sbHtml.Append("{" + string.Format(_strHtml, _template.Field, _template.THCaption,
                //        "100%"
                //        , string.IsNullOrEmpty(_template.DataFormatter) ? "sortable:true" : (_template.DataFormatter + ",sortable:true")) + "},");
                //}
                //else
                {
                    _sbHtml.Append("{" + string.Format(_strHtml, _template.Field, _template.THCaption,
                     (_template.Width > 0 ? _template.Width : 200)
                     , string.IsNullOrEmpty(_template.DataFormatter) ? "sortable:true,resizeable:true,editor: new YAHOO.widget.TextareaCellEditor()" : "formatter:" + (_template.DataFormatter + ",sortable:true,resizeable:true,editor: new YAHOO.widget.TextareaCellEditor()")) + "},");
                }
                if (i == 1)
                {
                    _sbHtml.Append("{" + string.Format(_strHtml, "iSun_Selected", "", 10, "formatter:\"checkbox\"") + "},");
                }


            }
            _sbHtml.Remove(_sbHtml.Length - 1, 1);
            return (_sbHtml.ToString());
        }

        /// <summary>
        /// 获得表头
        /// </summary>
        /// <returns></returns>
        public string GetColums()
        {
            if (list == null)
            {
                DataListTemplate template = DataListTemplate.CreateInstance();
                BaseBussnies<DataListTemplate> bll = new BaseBussnies<DataListTemplate>(template);
                list = bll.GetEntityListByCondition<DataListTemplate>("EntityName='" + EntityName + "'");
            }
            if (list == null)
            {
                return "";
            }

            StringBuilder _sbHtml = new StringBuilder("");
            var _list = list.OrderBy(p => p.iOrder);
            int i = 0;
            foreach (DataListTemplate _template in _list)
            {
                _sbHtml.Append("'" + _template.Field + "',");
                if (i == 0)
                {
                    _sbHtml.Append("'iSun_Selected',");
                    i = 1;
                }
            }
            _sbHtml.Remove(_sbHtml.Length - 1, 1);
            return (_sbHtml.ToString());
        }

        /// <summary>
        /// 获得表头
        /// </summary>
        /// <returns></returns>
        public string GetColumsCss()
        {
            if (list == null)
            {
                DataListTemplate template = DataListTemplate.CreateInstance();
                BaseBussnies<DataListTemplate> bll = new BaseBussnies<DataListTemplate>(template);
                list = bll.GetEntityListByCondition<DataListTemplate>(" EntityName='" + EntityName + "'");
            }
            string _strHtml = ".yui-skin-sam .yui-dt-col-{0}{width:{1}}\n";
            if (list == null)
            {
                return (string.Format(_strHtml, "Not Data", "Not Data", 400));
            }
            StringBuilder _sbHtml = new StringBuilder("");
            var _list = list.OrderBy(p => p.iOrder);
            int i = 0;
            foreach (DataListTemplate _template in _list)
            {
                i = i + 1;
                if (i == _list.Count())
                {
                    _sbHtml.Append(_strHtml.Replace("{0}", _template.Field).Replace("{1}", "100%"));
                }
                else
                {
                    _sbHtml.Append(_strHtml.Replace("{0}", _template.Field).Replace("{1}", _template.Width < 200 ? "200px" : _template.Width.ToString() + "px"));
                }
            }
            _sbHtml.Remove(_sbHtml.Length - 1, 1);
            return (_sbHtml.ToString());
        }

    }
}
